<template>


  <el-card class="box-card" shadow="hover">
    <el-alert :title="content" type="warning" :closable="false" />
    <div class="flex justify-between flex-wrap mb-2 mt">
      <el-space wrap :size="10" class="mt-1">
        <el-input
          v-model="params.fb_name"
          style="width: 150px"
          placeholder="用戶名稱"
        />
        <el-input
          v-model="params.msg_user_id"
          style="width: 150px"
          placeholder="PSID"
        />
        <el-input
          v-model="params.e_consume_price"
          style="width: 150px"
          placeholder="消费金额"
        />
        <el-input
          v-model="params.e_consume_num"
          style="width: 150px"
          placeholder="消费次数"
        />
        <el-select
          v-model="params.user_type_id"
          placeholder="类型"
          style="width: 150px"
        >
          <el-option
            v-for="item in filter.usertype"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-select-v2
          v-model="params.group_id"
          filterable
          :options="filter.group"
          placeholder="选择分组"
          style="width: 150px"
          :props="{ value: 'id', label: 'name' }"
          clearable
        />
        <el-button :icon="Search" plain @click="search">查詢</el-button>
      </el-space>
      <el-space wrap :size="10" class="mt-1">
        <el-button type="primary" plain @click="openUsersGroup"
          >设置分组</el-button
        >
        <el-button type="primary" plain>关联用户</el-button>
        <el-button type="primary" plain>下载</el-button>
      </el-space>
    </div>
    <el-table
      ref="multipleTableRef"
      @selection-change="handleSelectionChange"
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="头像" align="center" width="150">
        <template #default="scope">
          <el-image
            style="width: 100px"
            :src="scope.row.user_img"
            fit="contain"
          />
        </template>
      </el-table-column>
      <el-table-column label="名称/PSID" align="center">
        <template #default="scope">
          <div class="flex flex-column align-center">
            <div>{{ scope.row.fb_name }}</div>
            <div class="mt">{{ scope.row.msg_user_id }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="user_type_txt" label="用户类型" />
      <el-table-column label="电商消费(总额/次数)">
        <template #default="scope">
          <span>{{ scope.row.e_consume_price }}</span
          >/<span :class="{ consume: Number(scope.row.e_consume_num) > 0 }">{{
            scope.row.e_consume_num
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所在分组">
        <template #default="scope">
          <span v-if="scope.row.group_names == ''">-</span>
          <span v-else>{{ scope.row.group_names }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="is_newuser" label="是否为新用户" />
      <el-table-column fixed="right" label="操作" width="120">
        <template #default="scope">
          <div class="ec2-btncon">
            <el-button
              link
              size="small"
              type="primary"
              @click="handleInfo(scope.$index, scope.row)"
              >客户资料</el-button
            >
            <el-button
              link
              size="small"
              type="danger"
              @click="openGroup(scope.$index, scope.row)"
              >设置分组</el-button
            >
            <el-button
              v-if="scope.row.group_names !== ''"
              link
              size="small"
              type="info"
              @click="quitGroup(scope.$index, scope.row)"
              >退出分组</el-button
            >
            <el-button
              v-if="scope.row.user_type_id != 2"
              link
              size="small"
              type="warning"
              @click="unbind(scope.$index, scope.row)"
              >解除用户绑定</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="total > params.page_size" class="mt-2 flex justify-center">
      <el-pagination
        v-model:current-page="params.current_page"
        v-model:page-size="params.page_size"
        :page-sizes="[20, 40, 60]"
        :small="false"
        :disabled="false"
        :background="true"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-card>

  <set-group
    ref="groupRef"
    :row="currRow"
    :type="groupType"
    :euids="currEuids"
    :muti="groupMuti"
  ></set-group> 
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { Search, User, ArrowDown } from "@element-plus/icons-vue";
import { $userlist, $usertype, $updateUserGroup, $unbindUser } from "@api/user";
import { $getGroup } from "@api/common";
import router from "@/router/";
const groupMuti = ref(false);
const groupType = ref("");
const groupRef = ref();
let currEuids = ref([]);
let currRow = ref(null);
let params = ref({
  fb_name: "",
  msg_user_id: "",
  e_consume_num: "",
  e_consume_price: "",
  user_type_id: "",
  group_id: null,
  group_name: "",
  current_page: 1,
  page_size: 10,
});
const filter = ref({
  group: [],
  usertype: [],
});
const content = ref("");
const total = ref(0);
const tableData = ref([]);
onMounted(() => {
  getFilter();
});
const getFilter = async () => {
  const group_res = await $getGroup();
  const usertype_res = await $usertype();
  filter.value.group = group_res.data.list;
  filter.value.usertype = usertype_res.data.list;
  //初始化默认值
  params.value.user_type_id = usertype_res.data.list[0].id;
  getData();
};
const getData = async () => {
  let res = await $userlist(params.value);
  console.log(res);
  if (res.code == 0) {
    tableData.value = res.data.table;
    total.value = res.data.total;
    content.value = `总私讯用户数：${res.data.sum_private}，总活动用户数：${res.data.sum_activity} ，(统计时间：${res.data.sum_time})`;
  }
};
const handleSizeChange = (val: number) => {
  params.value.page_size = val;
  getData();
  console.log(`${val} items per page`);
};
const handleCurrentChange = (val: number) => {
  params.value.current_page = val;
  getData();
  console.log(`current page: ${val}`);
};
const handleSelectionChange = (val) => {
  currEuids.value = [];
  if (val.length !== 0) {
    val.forEach((ele) => {
      currEuids.value.push(ele.euid);
    });
  }
};
const search = () => {
  console.log(params.value);
  getData();
};

const openGroup = (index, row) => {
  groupMuti.value = true;
  groupType.value = "user";
  currRow.value = row;
  currEuids.value = [];
  groupRef.value.changeShow();
};
const openUsersGroup = () => {
  console.log(currEuids.value);
  if (currEuids.value.length == 0) {
    ElMessage({
      message: "请选择用户",
      type: "warning",
    });
    return false;
  }
  groupMuti.value = false;
  groupType.value = "users";
  currRow.value = {};
  groupRef.value.changeShow();
};

const handleInfo = (index, row) => {
  console.log(row);
  router.push({
    path: "/user/info",
    query: {
      id: row.euid,
    },
  });
};
const quitGroup = (index, row) => {
  ElMessageBox.confirm("确定要解除用户绑定吗?", "提示", {
    confirmButtonText: "OK",
    cancelButtonText: "Cancel",
    type: "warning",
    draggable: true,
  }).then(() => {
    quitUserGroup(row);
  });
};
const unbind = (index, row) => {
  ElMessageBox.confirm("确定要解除用户绑定吗?", "提示", {
    confirmButtonText: "OK",
    cancelButtonText: "Cancel",
    type: "warning",
    draggable: true,
  }).then(() => {
    unbindUserGroup(row);
  });
};
const unbindUserGroup = async (row) => {
  let res = await $unbindUser({ euid: row.euid });
  if (res.code == 0) {
    ElMessage({
      message: "操作成功",
      type: "success",
    });
    getData();
  } else {
    ElMessage.error(res.msg);
  }
};
const quitUserGroup = async (row) => {
  let res = await $updateUserGroup({ euid: row.euid });
  if (res.code == 0) {
    ElMessage({
      message: "操作成功",
      type: "success",
    });
    getData();
  } else {
    ElMessage.error(res.msg);
  }
};
const refreshPage = () => {
  //location.reload();
  const currentRoute = router.currentRoute.value;
  console.log(currentRoute);
  router.replace(currentRoute);
  //router.replace({name: '404'});
};
</script>
<style>
.ec2-search {
  margin-right: 5px;
  .el-input__wrapper {
    border-radius: 30px;
  }
}
.ec2-btncon {
  .el-button {
    margin-bottom: 2px;
    justify-content: flex-start;
  }
  .el-button + .el-button {
    margin-left: 0;
  }
}
</style>
<style lang="scss" scoped>
.mob-list {
  .mob-list-item{
    background:#fff;
    border-radius:8px;
    padding:15px;
    margin-bottom:10px;
  }
  .desc-item{
    padding:15px 0;
    border-bottom:1px solid #EBEEF5;
  }
}
.consume {
  padding-left: 2px;
  color: var(--el-color-primary);
}
.ec2-btncon {
  display: flex;
  flex-direction: column;
}
</style>
